﻿import { SettingsService } from '@delon/theme';
import { Component, Injector, Output, EventEmitter, ElementRef, OnInit, Inject } from '@angular/core';
import {FormBuilder,FormControl,FormGroup,Validators} from '@angular/forms';
import { HttpClient, HttpParams } from '@angular/common/http';
import { ProductEditDto } from "@shared/model/productdto";
import { NzMessageService, NzModalService, UploadFile } from 'ng-zorro-antd';
import { AppComponentBase } from "@shared/component-base/app-component-base";
import { SelectOptionDto } from "@shared/model/selectoptiondto";
import { UploadFileDto } from "@shared/model/uploadfiledto";
import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import AjaxUpload from 'ckeditor5-ajax-upload/src/ajaxupload';
import { environment } from '@env/environment';
import {TokenService,DA_SERVICE_TOKEN} from '@delon/auth';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
@Component({
  templateUrl: './edit-product.component.html'
})

export class EditProductComponent extends AppComponentBase implements OnInit {
  isVisible = false;
  active: boolean = false;
  validateForm: FormGroup;
  product: ProductEditDto = null;
  public Editor = ClassicEditor;
  previewImage = '';
  previewVisible = false;
  optionList: SelectOptionDto = null;
  public config = {
    language: 'zh-cn',
    extraPlugins: [AjaxUpload],
    startupFocus: true,
    AjaxUpload: {
      url: 'file/UploadCkEditorImage',
      headers: { 'Authorization': `Bearer ${this.tokenService.get().token}`}
    }
  };

  fileUploadUrl = `${environment.SERVER_URL}file/ImageUpaload`;
  fileList: UploadFileDto[] = [];
  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
  constructor(
    private injector: Injector,
    private httpClient: HttpClient,
    private fb: FormBuilder,
    @Inject(DA_SERVICE_TOKEN) private tokenService: TokenService,
    private routerParams: ActivatedRoute,
    private router: Router,
    public msg: NzMessageService
  ) {
    super(injector);
  }

  handleSave(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (!this.validateForm.valid) {
      return;
    }

    this.product.imageList = this.fileList;
    this.httpClient.post("product/edit", this.product.toJSON()).subscribe(
      (val) => {
        const result: any = val;
        if (result && !result.success) {
          this.msg.error(result.message);
          return null;
        } else {
          this.msg.create("success", "保存成功！");
          this.router.navigate(['/product/list']);
        }
      });
  }

  handleCancel(): void {
    this.active = false;
    this.isVisible = false;
  }

  handleChange(info: any): void {
    const fileList = info.fileList;
    const status = info.file.status;
    if (status === 'done') {
      this.fileList = fileList.map((file) => {
        if (file.response) {
          file.url = file.response.data.url;
          file.thumbUrl = file.response.data.thumbUrl;
        }
        return file;
      });
    }else if (status === 'error') {
      this.msg.error(`${info.file.name} 上次失败.`);
    }
  }

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }


  getCategoryOptions(): void {
    this.httpClient.get("category/option").subscribe(
      (val) => {
        const result: any = val;
        if (result && !result.success) {
          this.msg.error(result.message);
          return null;
        } else {
          this.optionList = result.data;
        }
      });
  }

  showModal(id: number): void {
    this.product = new ProductEditDto();
    let params = new HttpParams().append('id', `${id}`);
    this.httpClient.get("product/info", {params}).subscribe(
      (val) => {
        const result: any = val;
        if (result && !result.success) {
          this.msg.error(result.message);
          return null;
        } else {
          this.product.init(result.data);
          this.fileList = this.product.imageList;
        }
      });

    this.validateForm.reset();
    this.active = true;
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      categoryId: [null, [Validators.required]],
      sku: [null, [Validators.required]],
      price: [null, [Validators.required]],
      oldPrice: [null, [Validators.required]],
      productCost: [null],
      content: [null, [Validators.required]],
      stockQuantity: [null, [Validators.required]],
      soldQuantity: [null],
      keywords: [null],
      weight: [null],
      length: [null],
      width: [null],
      height: [null],
    });

    this.getCategoryOptions();
    this.active = true;
    this.validateForm.reset();
    var id = this.routerParams.snapshot.paramMap.get('id');
    this.showModal(+id);
  }
}


